<script setup>
import { ref } from 'vue';
import {
  getMenuListService,
  getRoleMenusService,
  setRoleMenusService
} from '@/apis/system-manage';
import { useAppMenuStore } from '@/stores/';

let mRoleId = '';
const menuTreeRef = ref();
const menuTreeData = ref([]);
const loading = ref(false);

let isGiveupWarning = false;
const handleClose = (done) => {
  if (!isGiveupWarning) {
    ElMessage.warning('当前的 角色菜单 未保存，放弃保存请再次点击取消');
    isGiveupWarning = true;
    setTimeout(() => {
      isGiveupWarning = false;
    }, 3000);
    return;
  }

  if (done) {
    done();
  } else {
    dialogVisible.value = false;
  }
};

let appMenuStore = useAppMenuStore();

const dialogVisible = ref(false);
const open = async (roleId) => {
  mRoleId = roleId;
  menuTreeData.value = [];
  dialogVisible.value = true;

  loading.value = true;
  Promise.all([
    getMenuListService({}),
    getRoleMenusService({ id: roleId })
  ]).then((resArr) => {
    loading.value = false;

    let allMenuRes = resArr[0];
    let roleMenuRes = resArr[1];

    menuTreeData.value = appMenuStore.filterTheMenu(allMenuRes.data);
    let settedMenus = appMenuStore.filterTheMenu(roleMenuRes.data);

    // 因为父级菜单会自动勾选上，因此获取最子层的菜单
    let resultMenus = getMostChildMenus(settedMenus);
    let resultMenuIds = resultMenus.map((a) => a.id);
    menuTreeRef.value.setCheckedKeys(resultMenuIds, false);
  });
};

// 获取最子层的菜单
const getMostChildMenus = (menus) => {
  let thisMenus = [];
  for (var i = 0; i < menus.length; i++) {
    let menu = menus[i];
    if (!menu.children || menu.children.length === 0) {
      if (menu.menuIcon) {
        thisMenus.push(menu);
      }
      continue;
    }

    thisMenus = thisMenus.concat(getMostChildMenus(menu.children));
  }
  return thisMenus;
};

defineExpose({
  open
});

const onConfirm = async () => {
  let settedMenuTreeNodes = menuTreeRef.value.getCheckedNodes(false, true);
  let menuIds = settedMenuTreeNodes.map((a) => a.id);

  loading.value = true;
  let res = await setRoleMenusService({ roleId: mRoleId, menuIds: menuIds });
  loading.value = true;
  ElMessage.success(res.msg);
  dialogVisible.value = false;
};
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="设置角色菜单"
    width="30%"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-tree
      v-loading="loading"
      ref="menuTreeRef"
      :data="menuTreeData"
      show-checkbox
      node-key="id"
      :default-expand-all="true"
      :props="{ children: 'children', label: 'menuName' }"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="onConfirm">确认</el-button>
        <el-button @click="handleClose()">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>
